// pages/material/index.js
import {
  chemicalAlias
} from '../../dataSource'
import {
  request
} from '../../api/index'
import {
  numSettingsType
} from '../../dataSource'
import {
  _list
} from '../../api/ingredients-parent'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataSource: [],
    selectValue: {
      val: '',
      id: '',
      columns: []
    },
    pickerShow: false,
    id: '',
    paramsObj: [],
    popupEvent: {},
    popupState: false,
    status: null,
    root: getApp().globalData.root,
    total: 0,
    numSettingsType
  },
  onConfirm(arg) {
    request.ingredientsAdd({
      ...arg,
      parentId: this.data.selectValue['id'],
      productionNumberDatas: this.getNumberSetting(),
      status: 'TO_BE_ANNOUNCED'
    }, () => {
      wx.showModal({
        title: '原料已创建',
        content: '是否返回上一页？',
        success: (res) => {
          if (res.confirm) {
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })
    })
  },
  onClose() {
    this.triggerEvent('onClose')
  },
  onOpenParentPicker() {
    this.setData({
      pickerShow: true
    })
  },
  onCloseParentPicker() {
    this.setData({
      pickerShow: false
    })
  },
  onPickerChange(event) {
    const values = event.detail.value;
    this.setData({
      selectValue: {
        ...this.data.selectValue,
        val: values['text'],
        id: values['value']
      },
      pickerShow: false
    })
  },
  onPopupClose() {
    this.setData({
      popupState: false
    })
  },
  onPopupOpen(popupEvent) {
    this.setData({
      popupEvent,
      popupState: true
    })
  },
  /**
   * 
   * @param {Array<List>} list 
   * @returns Number
   */
  getTotal(list) {
    let li = list.filter(it => it.value !== 'name');
    const total = li.reduce((preval, currentVal) => {
      return preval + Number(currentVal.val)
    }, 0).toFixed(2)
    return total;
  },
  onSubmit(event) {
    const target = event.detail.value,
      type = event.detail.target.dataset.type;

    if (type === 'edit' && this.data.status !== 'TO_BE_ANNOUNCED') {
      return
    }
    for (let item in target) {
      if (target[item] === "") {
        target[item] = '0'
      }
    }
    switch (type) {
      case 'edit':
        this.onEdit(target)
        break;
      case 'new':
        this.onNew(target);
        break;
      case 'announced':
        this.onAnnounced(target);
        break;
      default:
        this.onConfirm(target);
        break;
    }
  },
  onAnnounced(target) {
    //遍历检查是否所有的参数都为0
    const valid = Object.keys(target).every(it => {
      return target[it] === '0' || target[it] || false
    })

    if (valid) {
      wx.showModal({
        title: '数据不合法提示',
        content: '检测到数据均为0',
        showCancel: false
      })
      return
    }
    const tar = {
      id: this.data.id,
      ...target,
      productionNumberDatas: this.getNumberSetting(),
      status: 'ANNOUNCED'
    }
    request[!!this.data.id ? 'ingredientsUpdate' : 'ingredientsAdd'](tar, e => {
      wx.showModal({
        title: '原料已发布',
        content: '是否返回上一页？',
        success: (res) => {
          if (res.confirm) {
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })
    })
  },
  getNumberSetting() {
    const numberSettings = this.selectComponent("#vc-number")?.getDataSource();

    const number_data = numberSettings.map(it => {
      return {
        name: it.name,
        numSelectManageId: it.numSelectManageId,
        remark: it.remark,
        sortNumber: it.sortNumber,
        value: it.value
      }
    })
    return number_data
  },
  onEdit(target) {

    const tar = Object.assign({
      id: this.data.id,
    }, target, {
      parentId: this.data.selectValue['id'],
    })
    request.ingredientsUpdate(tar, e => {
      wx.showModal({
        title: '原料已创建',
        content: '是否返回上一页？',
        success: (res) => {
          if (res.confirm) {
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })
    })
  },
  onNew(target) {
    wx.showModal({
      title: '副本名称',
      content: '',
      editable: true,
      success(res) {
        if (res.confirm) {
          const newTarget = {
            ...target,
            parentId: this.data.selectValue['id'],
            name: res.content,
            productionNumberDatas: this.getNumberSetting(),
            status: 'ANNOUNCED'
          }
          request.ingredientsAdd(newTarget, () => {
            wx.showModal({
              title: '原料已创建',
              content: '是否返回上一页？',
              success: (res) => {
                if (res.confirm) {
                  wx.navigateBack({
                    delta: 1
                  })
                }
              }
            })
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  async setDataSource() {
    const list = Object.keys(chemicalAlias);
    const arr = [];
    for (let key of list) {
      if (key === 'name') {
        arr.push({
          name: '编号',
          value: key,
          val: ''
        })
        //continue
      } else {
        arr.push({
          name: chemicalAlias[key],
          value: key,
          val: ''
        })
      }
    }
    this.setData({
      list: arr
    })
    const total = this.getTotal(arr);
    this.setData({
      total
    })
    await this.fetchParentList();
    if (this.data.id) {
      this.fillData()
    } else {
      wx.setNavigationBarTitle({
        title: '新建原料'
      })
    }
  },
  onChange(event) {
    const value = event.detail,
      val = event.currentTarget.dataset.value,
      list = [...this.data.list];
    const newList = list.map(it => {
      return {
        ...it,
        val: it.value === val ? value : it.val
      }
    })
    //不包含烧失量
    const total = this.getTotal(newList);
    this.setData({
      list: newList,
      total
    })

  },
  async fetchParentList() {
    return new Promise((resolve, reject) => {
      _list({}, res => {
        const columns = [{
          value: null,
          text: '[暂不设置]'
        }, ...res.map(it => {
          return {
            value: it['id'],
            text: it['name']
          }
        })];
        this.setData({
          selectValue: {
            ...this.data.selectValue,
            columns
          }
        })
        resolve();
      }, reject)
    })
  },
  /**
   * 编辑或查看的时候
   */
  fillData() {
    request.ingredientsDesc(this.data.id, e => {
      const list = this.data.list.map(it => {
        return {
          ...it,
          val: e[it.value] || 0
        }
      })

      //初始统计
      const total = this.getTotal(list);
      this.setData({
        list,
        status: e.status,
        total,
        dataSourceNumber: e,
        selectValue: {
          ...this.data.selectValue,
          val: this.data.selectValue['columns'].find(it => it['value'] === e['parentId'])?.text,
          id: e['parentId']
        }
      })
      wx.setNavigationBarTitle({
        title: e.name
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let paramsObj = [];
    if (options.params) {
      const params = decodeURIComponent(options.params);
      paramsObj = JSON.parse(params);
    }
    this.setData({
      id: options.id,
      paramsObj,
      root: wx.getStorageSync('root')
    })
    this.setDataSource();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.onAppRoute((res) => {
      if (res.path === 'pages/material/index') {
        this.setData({
          root: getApp().globalData.root
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})